import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { login, sendCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile-v2'
import { useHistory } from 'react-router'
import { useLocation } from 'react-router-dom'

export default function Login() {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  // 倒计时
  const [count, setCount] = useState(0)

  // form整个表单控制
  const form = useFormik({
    // 表单的初始值
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    // 校验函数, 校验的逻辑在函数中提供
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('请输入手机号')
        .matches(/^1[3-9]\d{9}$/, '请输入正确的11位手机号'),
      code: Yup.string()
        .required('请输入验证码')
        .matches(/^\d{6}$/, '请输入6位验证码'),
    }),
    onSubmit: async (values) => {
      await dispatch(login(values))
      Toast.success('恭喜! 登录成功!')
      const pathname = location?.state?.pathname || '/home'
      history.replace(pathname)
    },
  })

  // 处理发送验证码
  const handleSendCode = async () => {
    if (count === 0) {
      const mobile = form.values.mobile
      if (!/^1[3-9]\d{9}$/.test(mobile)) return

      await dispatch(sendCode(mobile))

      Toast.success('发送验证码成功', 2)

      // 开始倒计时
      setCount(60) // 设置从哪开始倒计时
      // 每隔1秒, 让count-1
      let timeId = setInterval(() => {
        setCount((count) => {
          // 原本是1, 并且本次, 要将1改成0了, 此时需要清除定时器
          if (count === 1) {
            clearInterval(timeId)
          }
          return count - 1
        })
      }, 1000)
    }
  }

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={form.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <Input
              value={form.values.mobile}
              onChange={form.handleChange}
              onBlur={form.handleBlur}
              name="mobile"
              placeholder="请输入手机号"
              type="text"
              maxLength={11}
              autoComplete="off"
            ></Input>
            {form.touched.mobile && form.errors.mobile && (
              <div className="validate">{form.errors.mobile}</div>
            )}
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <Input
              value={form.values.code}
              onChange={form.handleChange}
              onBlur={form.handleBlur}
              name="code"
              placeholder="请输入验证码"
              maxLength={6}
              extra={count > 0 ? count + '秒再次发送' : '获取验证码'}
              autoComplete="off"
              onExtraClick={handleSendCode}
            ></Input>
            {form.touched.code && form.errors.code && (
              <div className="validate">{form.errors.code}</div>
            )}
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            disabled={!form.isValid}
            className={classNames([
              'login-btn',
              form.isValid ? '' : 'disabled',
            ])}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
